/*************************************************************************
	> File Name: test5.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/22 19:11
 ************************************************************************/

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <pthread.h>

void *thread1(void *args)
{
    printf("thread1 returning...\n");
    int *p = (int*)malloc(sizeof(int));
    *p = 1;
    return (void*)p;
}

void *thread2(void *args)
{
    printf("thread2 returning...\n");
    int *p = (int*)malloc(sizeof(int));
    *p = 2;
    pthread_exit((void*)p);
}

void *thread3(void *args)
{
    while (1) {
        printf("thread 3 is running...\n");
        sleep(1);
    }
    return nullptr;
}

int main(int argc, char *argv[])
{
    pthread_t tid;
    void *ret;
    pthread_create(&tid, nullptr, thread1, nullptr);
    pthread_join(tid, &ret);
    printf("thread return, thread id %x, return code:%d\n", tid, *(int*)ret);
    delete ret;
    pthread_create(&tid, nullptr, thread2, nullptr);
    pthread_join(tid, &ret);
    printf("thread return, thread id %x, return code:%d\n", tid, *(int*)ret);
    delete ret;
    pthread_create(&tid, nullptr, thread3, nullptr);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid, &ret);
    if (ret == PTHREAD_CANCELED) {
        printf("thread return, thread id %X, return code:PTHREAD_CANCELED\n", tid);
    } else {
        printf("thread return, thread id %X, return code:NULL\n", tid);
    }
    return 0;
}
